package com.moon.icoresso.strategy.impl;

import com.moon.icoresso.Exception.OauthException;
import com.moon.icoresso.Service.OauthRedisService;
import com.moon.icoresso.Service.OauthService;
import com.moon.icoresso.common.utils.StringRedisService;
import com.moon.icoresso.pojo.bo.OauthCodeToRedisBO;
import com.moon.icoresso.pojo.bo.OauthTokenHandleBO;
import com.moon.icoresso.pojo.dto.OauthTokenDTO;
import com.moon.icoresso.pojo.dto.OauthTokenParam;
import com.moon.icoresso.pojo.dto.OauthUserInfo;
import com.moon.icoresso.strategy.OauthStrategy;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.moon.icoresso.pojo.constants.Constants4Oauth.OAUTH_CODE_GRANT_TYPE;


/**
 * @ClassName OauthCodeStrategy
 * @Description
 * @Author menbbo
 * @Date 2021/2/13 17:06
 * @Version V1.0
 **/
@Component(OAUTH_CODE_GRANT_TYPE)
public class OauthCodeStrategy implements OauthStrategy{
    @Autowired
    private OauthRedisService oauthRedisService;
    @Autowired
    private StringRedisService<String,OauthUserInfo> stringRedisService;
    @Autowired
    private OauthService oauthService;

    @Override
    public void checkParam(OauthTokenParam oauthTokenParam, OauthTokenHandleBO oauthTokenHandleBO) {
            OauthCodeToRedisBO oauthCodeByCode = oauthRedisService.findOauthCodeByCode(oauthTokenParam.getCode());
            if(oauthCodeByCode==null){
                throw new OauthException("该code已失效");
            }
            if(!StringUtils.equalsIgnoreCase(oauthCodeByCode.getClientId(),oauthTokenParam.getClientId())){
                throw new OauthException("clientId不匹配");
            }
            oauthTokenHandleBO.setUserInfoRedisKey(oauthCodeByCode.getUserInfoRedisKey());
    }

    @Override
    public OauthTokenDTO handle(OauthTokenParam oauthTokenParam, OauthTokenHandleBO oauthTokenHandleBO) {
        //获得用户信息
        OauthUserInfo oauthUserInfo = stringRedisService.get(oauthTokenHandleBO.getUserInfoRedisKey());
        if(oauthUserInfo==null){
            throw new OauthException("用户信息获取失败");
        }
        OauthTokenDTO oauthTokenDTO = oauthService.generateToken(true);
        //将token保存
        oauthRedisService.saveAccessToken(oauthTokenParam.getGrantType(),oauthTokenParam.getClientId(),oauthTokenDTO.getAccessToken(),oauthTokenHandleBO.getOauthUserInfo());
        oauthRedisService.saveRefreshToken(oauthTokenDTO.getRefreshToken(),oauthTokenParam.getGrantType(),oauthTokenParam.getClientId(),oauthTokenHandleBO.getOauthUserInfo());
        //删除授权码
        oauthRedisService.deleteCode(oauthTokenParam.getCode());
        return oauthTokenDTO;
    }
}